<?php
	
	require_once 'Zend/Controller/Plugin/Abstract.php';

	class Default_Plugin_AclManager extends Zend_Controller_Plugin_Abstract
	{
		private $_defaultRole = 'guest';
        private $_authController = array('controller' => 'auth',
                                         'action' => 'login');
		public function __construct()
		{
			$this->auth = Zend_Auth::getInstance();
			$this->acl = Zend_Registry::get('acl');
			
			$this->acl->addRole(new Zend_Acl_Role('guest'));
			$this->acl->addRole(new Zend_Acl_Role('member'));
			$this->acl->addRole(new Zend_Acl_Role('admin'));
			
			$this->acl->add(new Zend_Acl_Resource('index'));
			$this->acl->add(new Zend_Acl_Resource('game'));
			$this->acl->add(new Zend_Acl_Resource('error'));
			$this->acl->add(new Zend_Acl_Resource('statistics'));
			$this->acl->add(new Zend_Acl_Resource('mypage'));
			$this->acl->add(new Zend_Acl_Resource('auth'));
			$this->acl->add(new Zend_Acl_Resource('contact'));
		
			$this->acl->allow('guest', 'index');
			$this->acl->allow('member', 'index');
			$this->acl->allow('admin', 'index');

			$this->acl->allow('guest', 'auth');
			$this->acl->allow('member', 'auth');
			$this->acl->allow('admin', 'auth');

			$this->acl->allow('guest', 'game');
			$this->acl->allow('member', 'game');
			$this->acl->allow('admin', 'game');

			$this->acl->allow('guest', 'error');
			$this->acl->allow('member', 'error');
			$this->acl->allow('admin', 'error');

			$this->acl->allow('guest', 'statistics');
			$this->acl->allow('member', 'statistics');
			$this->acl->allow('admin', 'statistics');

			$this->acl->deny('guest', 'mypage');
			$this->acl->allow('member', 'mypage');
			$this->acl->allow('admin', 'mypage');
			
			$this->acl->allow('guest', 'contact');
			$this->acl->allow('member', 'contact');
			$this->acl->allow('admin', 'contact');
		}
		
		public function preDispatch(Zend_Controller_Request_Abstract $request)
        {     		
            if ($this->auth->hasIdentity()) {
                $role = $this->auth->getIdentity()->spagooy_user_role;
            } else {
                $role = $this->_defaultRole;
			}
			
            if (!$this->acl->hasRole($role)) {
                $role = $this->_defaultRole;
			}
            $resource = $request->controller;
            $privilege = $request->action;
            if (!$this->acl->has($resource)) {
                $resource = null;
			}
            if (!$this->acl->isAllowed($role, $resource, $privilege)) {
				$request->setControllerName($this->_authController['controller']);
                $request->setActionName($this->_authController['action']);
            }

        }
	}
